// 城市页
//  MZY_City.m
//  FullHouse
//
//  Created by dllo on 16/2/26.
//  Copyright © 2016年 yy. All rights reserved.
//

#import "MZY_City.h"
#import "NetworkingTool.h"
#import "MZY_cityModel.h"
#import "NH_OrderByPinYinFirstLetter.h"

@interface MZY_City ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating>

@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *cityArr;
@property(nonatomic, retain)NSMutableArray *orderArr;

@property(nonatomic, retain)UISearchController *searchController;
@property(nonatomic, retain)NSMutableArray *searchArr;
@property(nonatomic, retain)NSMutableArray *dataArr;

@property(nonatomic, retain)NSMutableArray *cityNameArr;
@property(nonatomic, retain)NSMutableArray *cityNameIDArr;

@end

@implementation MZY_City

- (void)dealloc
{
    [self.tableView release];
    [self.cityArr release];
    [self.orderArr release];
    [self.searchArr release];
    [self.searchController release];
    [self.dataArr release];
    [self.cityNameIDArr release];
    [self.cityNameArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createData];
    [self createView];
}

#pragma mark 获取数据
- (void)createData{
    [NetworkingTool networkingWithStrURL:@"http://api.meilijia.com/app/advanced_pro_zone_list" type:GETType bodyStr:nil block:^(id result) {
        self.cityArr = [NSMutableArray array];
        self.cityNameArr = [NSMutableArray array];
        self.cityNameIDArr = [NSMutableArray array];
        NSArray *arr = result[@"data"][@"advanced_pro_zone_list"][@"show_city"];
        for (NSDictionary *dic in arr) {
            [self.cityArr addObjectsFromArray:dic[@"city_list"]];
            for (NSDictionary *temp in dic[@"city_list"]) {
                [self.cityNameArr addObject:temp[@"name"]];
                NSDictionary * dic = @{temp[@"name"] : temp[@"id"]};
                [self.cityNameIDArr addObject:dic];
            }
        }
        self.orderArr = [NH_OrderByPinYinFirstLetter baseOrderPinYinOnArr:self.cityArr ByKey:@"name"];
        [self.tableView reloadData];
    }];
}

#pragma mark 创建界面
- (void)createView{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"城市列表";
    
    // 创建返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 20, 20);
    [backButton setImage:[UIImage imageNamed:@"iconfont-arrowleft.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];

    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.hidesNavigationBarDuringPresentation  = NO;
    self.searchController.dimsBackgroundDuringPresentation = false;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44);
    self.searchController.searchBar.placeholder = @"请输入城市";
    self.tableView.tableHeaderView = self.searchController.searchBar;
    [self.searchController release];
    [self.tableView release];
}

#pragma mark 返回"cell"个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active) {
        return [self.searchArr count];
    }else{
        return [self.orderArr[section][@"datas"] count];
    }
}

#pragma mark 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.searchController.active) {
        return 1;
    }else{
        return self.orderArr.count;
    }
}

#pragma mark "tableView"第二个必须执行的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    self.dataArr = self.orderArr[indexPath.section][@"datas"];
    if (self.searchController.active) {
        [cell.textLabel setText:self.searchArr[indexPath.row]];
        // 搜索时  关键字高亮
        NSMutableAttributedString *att=[[NSMutableAttributedString alloc]initWithString:[self.searchArr objectAtIndex:indexPath.row]];
        [att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:[[self.searchArr objectAtIndex:indexPath.row]rangeOfString:[self.searchController.searchBar text]]];
        [att addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[[self.searchArr objectAtIndex:indexPath.row]rangeOfString:[self.searchController.searchBar text]]];
        cell.textLabel.attributedText=att;
    }else{
        [cell.textLabel setText:self.dataArr[indexPath.row][@"name"]];
    }
    return cell;
}

#pragma mark 搜索结果过滤
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *searchStr = [self.searchController.searchBar text];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",searchStr];
    NSLog(@"%@",predicate);
    if (self.searchArr != nil) {
        [self.searchArr removeAllObjects];
    }
    // 过滤数据
    self.searchArr = [NSMutableArray arrayWithArray:[self.cityNameArr filteredArrayUsingPredicate:predicate]];
    [self.tableView reloadData];
}

#pragma mark "tableView"的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    // 传"id"和"name"
    if (self.searchController.active) {
        NSString * name = self.searchArr[indexPath.row];
        for (NSDictionary * tempDic in self.cityNameIDArr) {
            if (tempDic[name] != NULL) {
                NSString * cityID = tempDic[name];
                 [self.delegate bringIdStr:cityID];
                self.block(self.searchArr[indexPath.row]);
                break;
            }
        }
    }else{
        self.dataArr = self.orderArr[indexPath.section][@"datas"];
        [self.delegate bringIdStr:self.dataArr[indexPath.row][@"id"]];
        // 调用"block"
        self.block(self.dataArr[indexPath.row][@"name"]);
    }
    
}

#pragma mark 分区标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (self.searchController.active) {
        return nil;
    }
    return self.orderArr[section][@"title"];
}

#pragma mark 分区快捷条
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSMutableArray *titleArr = [NSMutableArray array];
    for (NSDictionary *dic in self.orderArr) {
        [titleArr addObject:dic[@"title"]];
    }
    return titleArr;
}

#pragma mark 设置"cell"之间"headerView"的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

#pragma mark 返回按钮
- (void)backAction:(UIButton *)button{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
